package com.shadow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shadow.common.entity.Role;
import com.shadow.common.entity.UserRole;
import com.shadow.mapper.RoleMapper;
import com.shadow.mapper.UserRoleMapper;
import com.shadow.service.RoleService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private UserRoleMapper userRoleMapper;

    /**
     * 通过用户获取角色列表
     *
     * @param userId 用户id
     * @return {@link List} 角色列表
     */
    @Override
    public List<Role> getRoleListByUserId(String userId) {
        LambdaQueryWrapper<UserRole> userRoleWrapper = new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getUserId, userId);
        List<UserRole> userRoleList = userRoleMapper.selectList(userRoleWrapper);
        if (CollectionUtils.isNotEmpty(userRoleList)) {
            LambdaQueryWrapper<Role> roleWrapper = new LambdaQueryWrapper<Role>()
                    .in(Role::getId, userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList()));
            return Collections.unmodifiableList(roleMapper.selectList(roleWrapper));
        }
        return Collections.emptyList();
    }
}
